package tool

import (
	"gitee.com/tjloved/tool/es"
	"gitee.com/tjloved/tool/logger"
	"github.com/olivere/elastic/v7"
	"sync"
)

var esMap sync.Map

func Es(connection ...string) *elastic.Client {
	connectionName := "default"
	if len(connection) > 0 {
		connectionName = connection[0]
	}
	if _, ok := esMap.Load(connectionName); !ok {
		config := es.NewConfig()
		if err := Config().UnmarshalKey("es."+connectionName, &config); err != nil {
			panic(err)
		}
		config.Logger = logger.NewEsZapLoggerAdapter(Logger("es"))
		esMap.Store(connectionName, es.New(config))
	}
	c, _ := esMap.Load(connectionName)
	if client, ok := c.(*elastic.Client); ok {
		return client
	} else {
		panic("es 初始化错误")
	}
}
